package com.changxianggu.cloud.crawler.core.utils;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.apache.poi.ss.usermodel.DateUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 日期转换工具类
 *
 * 为了解决学生导入日期格式不规范报错问题
 *
 * 2018年3月6日 11:55:55
 */
public class MyDateConverter implements Converter {

    @Override
    public Object convert(Class type, Object value) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if( value == null ) {
            throw new ConversionException("No value specified");
        }
        double date;
        if( value instanceof Double ){
            date = ((Double)value).doubleValue();
        }else if( value instanceof Number){
            date = ((Number)value).doubleValue();
        }else if( value instanceof String ){
            // 传入date 值
            String dateStr = (String)value;
            try {
                date = Double.parseDouble( dateStr );
            } catch (NumberFormatException e) {
                if(dateStr.indexOf("-") == -1 && dateStr.indexOf("/") == -1 && dateStr.indexOf(".") == -1){
                    throw new ConversionException("日期格式非法：" + dateStr);
                }
                String[] dateStrArray = dateStr.split("\\.|-|/");
                // 非定义日期格式  例如 2017-02-03
                if(dateStrArray.length != 1){
                    // 处理过后的date 值
                    StringBuilder newDateStr = new StringBuilder();
                    for (String part: dateStrArray) {
                        newDateStr.append(part.trim()).append("-");
                    }
                    newDateStr.deleteCharAt(newDateStr.length() -1);
                    dateStr = newDateStr.toString();
                }
                try {
                    return sdf.parse( dateStr );
                } catch (ParseException e1) {
                    throw new ConversionException("日期格式非法");
                }
            }
        }else if(value instanceof java.util.Date) {
            return value;
        }else{
            throw new ConversionException("No value specified");
        }
        return DateUtil.getJavaDate( date );
    }
}
